package com.summer.transaction;

import java.util.ArrayList;

public class Transaction {
	private ArrayList<BaseAction> actionList = new ArrayList<BaseAction>();
	private TransactionAction transactionAction = null;
	
	public void addAction(BaseAction action){
		actionList.add(action);
	}
	
	public void setTransactionAction(TransactionAction transactionAction){
		this.transactionAction = transactionAction;
	}
	
	public boolean submit() throws TransactionException{
		
		if(transactionAction!=null)
			transactionAction.doBefore();
		
		for(BaseAction action : actionList){
			action.doBefore();
			action.doAction();
			action.doAfter();
		}
		
		if(transactionAction!=null)
			transactionAction.doAfter();
		
		return true;
	}
	
	public interface TransactionAction {
		public void doBefore();
		public void doAfter();
	}
	
	
	public static void main(String[] args) {
		Transaction transaction = new Transaction();
		transaction.addAction(new EatAction());
		transaction.addAction(new WashAction());
		transaction.setTransactionAction(new TransactionAction(){
			@Override
			public void doBefore() {
				System.out.println("做饭");
			}

			@Override
			public void doAfter() {
				System.out.println("去睡觉");
			}
		});
		try {
			transaction.submit();
		} catch (TransactionException e) {
			// 事务处理异常
			e.printStackTrace();
		}
	}
}
